﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

/// <summary>
/// JWT 令牌生成工具
/// </summary>
public class JwtHelper
{
    private readonly IConfiguration _configuration;

    public JwtHelper(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    /// <summary>
    /// 生成 JWT 令牌
    /// </summary>
    /// <param name="openid">微信用户的 OpenID</param>
    /// <returns>JWT 令牌字符串</returns>
    public string GenerateToken(string openid)
    {
        var jwtSettings = _configuration.GetSection("JwtSettings");

        var secretKey = Encoding.UTF8.GetBytes(jwtSettings["SecretKey"]); // 加密密钥
        var expireMinutes = int.Parse(jwtSettings["ExpireMinutes"]); // 令牌过期时间

        // 创建 JWT 负载（Claims）
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, openid), // 将 openid 存入 JWT
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) // 唯一标识
        };

        // 生成 Token
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.UtcNow.AddMinutes(expireMinutes), // 设置过期时间
            Issuer = jwtSettings["Issuer"],
            Audience = jwtSettings["Audience"],
            SigningCredentials = new SigningCredentials(
                new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256) // 使用 HMAC-SHA256 进行签名
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
}
